#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <strings.h>
#include "Common.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        return 1;
    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // tcp的套接字
    if (sockfd < 0)
    {
        std::cout << "创建套接字失败 error" << std::endl;
        return 2;
    }

    // 客户端吧需要显示的bind会在调用connect时自动随机绑定。
    // tcp是面向链接的

    sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    int n = ::connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "连接服务器失败 error" << std::endl;
    }

    // 读写消息
    while (true)
    {
        char inbuffer[1024];
        std::string input_msg;
        std::cout << "input message:" << std::endl;
        std::getline(std::cin, input_msg);

        int n=::write(sockfd, input_msg.c_str(), input_msg.size());
        if(n>0)
        {
            int m=::read(sockfd,inbuffer,sizeof(inbuffer));
            if(m>0)
            {
                inbuffer[m]='\0';
                std::cout<<"回了一个相同的消息:"<<inbuffer<<std::endl;
            }
            else 
            {
                std::cout<<"没有收到消息"<<std::endl;
                break;
            }
        }
        else 
        {
            std::cout<<"没有去写消息"<<std::endl;
            break;
        }
    }
    ::close(sockfd);
    return 0;
}